package com.jixi.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jixi.common.result.Result;
import com.jixi.common.utils.CozeChatUtil;
import com.jixi.common.utils.CozeOauthAccessTokenUtil;
import com.jixi.mapper.EducationCozeMapper;
import com.jixi.mapper.EducationMapper;
import com.jixi.pojo.dto.CozeChatDto;
import com.jixi.pojo.entity.Education;
import com.jixi.pojo.entity.EducationCoze;
import com.jixi.pojo.vo.CozeChatMessageVo;
import com.jixi.service.EducationCozeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.Map;

@Slf4j
@Service
public class EducationCozeServiceImpl extends ServiceImpl<EducationCozeMapper, EducationCoze> implements EducationCozeService {
	
	@Autowired
	private EducationCozeMapper educationCozeMapper;
	
	@Autowired
	private EducationMapper educationMapper;
	
	/**
	 * 发起对话
	 *
	 * @param cozeChatDto 用户输入
	 * @return 对话信息
	 */
	@Override
	public Result<CozeChatMessageVo> startCozeChat(CozeChatDto cozeChatDto) {
		
		// sa-token工具，获取当前登录用户的id，如果未登录会抛异常
		Long educationId = StpUtil.getLoginIdAsLong();
		// 获取用户输入
		String question = cozeChatDto.getQuestion();
		
		// 根据id查询用户信息（education_coze表）
		EducationCoze educationCoze = educationCozeMapper.selectById(educationId);
		
		// 第一次使用
		if (educationCoze == null) {
			// 获取当前时间戳
			Long now_time = Instant.now().getEpochSecond();
			// 获取access_token与其他信息
			String accessToken = CozeOauthAccessTokenUtil.getAccessToken(educationId);
			// 新建一条数据保存到数据库
			EducationCoze newEducationCoze = new EducationCoze();
			newEducationCoze.setEducationId(educationId);
			Education loginEducation = educationMapper.selectById(educationId);
			newEducationCoze.setEducationUsername(loginEducation.getEducationUsername());
			newEducationCoze.setEducationAccessToken(accessToken);
			newEducationCoze.setCreateTime(now_time);
			newEducationCoze.setUpdateTime(now_time);
			newEducationCoze.setIsDeleted(0);
			
			educationCozeMapper.insert(newEducationCoze);
			// 重新赋值
			educationCoze = newEducationCoze;
		}
		
		// 判断access_token是否过期（提前一小时）
		Long now_time = Instant.now().getEpochSecond();
		if ((educationCoze.getUpdateTime() + 60 * 60 * 23) < now_time) {
			// 过期了，重新获取access_token
			String accessToken = CozeOauthAccessTokenUtil.getAccessToken(educationId);
			educationCoze.setEducationAccessToken(accessToken);
			educationCoze.setUpdateTime(now_time);
			educationCozeMapper.updateById(educationCoze);
		}
		
		// 获取access_token
		String accessToken = educationCoze.getEducationAccessToken();
		// 调用智能体发起对话接口
		Map<String, Object> resultForStartChat = CozeChatUtil.startChat(accessToken, educationCoze.getEducationUsername(), question);
		
		// 从返回结果获取会话ID和对话ID以及对话的运行状态
		String conversationId = (String) resultForStartChat.get("conversation_id");
		String chatId = (String) resultForStartChat.get("chat_id");
		String status = (String) resultForStartChat.get("status");
		
		// 构造返回值
		CozeChatMessageVo resultMessage = new CozeChatMessageVo();
		resultMessage.setConversationId(conversationId);
		resultMessage.setChatId(chatId);
		resultMessage.setStatus(status);
		resultMessage.setContent("成功发起对话");
		
		return Result.success(resultMessage);
	}
	
	/**
	 * 检查对话状态/获取对话信息
	 *
	 * @param conversationId 会话ID
	 * @param chatId         对话ID
	 * @return 对话信息
	 */
	@Override
	public Result<CozeChatMessageVo> getCozeChatMessage(String conversationId, String chatId) {
		
		// sa-token工具，获取当前登录用户的id，如果未登录会抛异常
		Long educationId = StpUtil.getLoginIdAsLong();
		// 获取access_token
		EducationCoze educationCoze = educationCozeMapper.selectById(educationId);
		String accessToken = educationCoze.getEducationAccessToken();
		
		// 查看对话详情
		Map<String, Object> resultForGetChatStatus = CozeChatUtil.getChatStatus(accessToken, conversationId, chatId);
		String status = (String) resultForGetChatStatus.get("status");
		
		// 构造返回值
		CozeChatMessageVo resultMessage = new CozeChatMessageVo();
		resultMessage.setConversationId(conversationId);
		resultMessage.setChatId(chatId);
		resultMessage.setStatus(status);
		
		if ("in_progress".equals(status) || "created".equals(status)) {
			// 智能体正在处理
			resultMessage.setContent("正在处理中，请稍等......");
		} else {
			// 智能体处理完成
			// 查看对话消息详情
			Map<String, Object> resultForGetChatMessage = CozeChatUtil.getChatMessage(accessToken, conversationId, chatId);
			// 这里只处理了content文本消息，如果后续要处理card卡片消息之类的东西可随时扩展
			resultMessage.setContent(
					(String) resultForGetChatMessage.get("content")
			);
		}
		
		return Result.success(resultMessage);
	}
}
